Repeated substring pattern

Time: O(N); Space: O(N); easy

Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.

You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.

Example 1:

Input: s = “abab”

Output: True

Explanation:

  • It’s the substring “ab” twice.

Example 2:

Input: s = “aba”

Output: False

Example 3:

Input: s = “abcabcabcabc”

Output: True

Explanation:

  • It’s the substring “abc” four times. (And the substring “abcabc” twice.)

[1]:
class Solution1(object):
    """
    KMP solution
    """
    def repeatedSubstringPattern(self, s):
        """
        :type s: str
        :rtype: bool
        """
        def getPrefix(pattern):
            prefix = [-1] * len(pattern)
            j = -1
            for i in range(1, len(pattern)):
                while j > -1 and pattern[j + 1] != pattern[i]:
                    j = prefix[j]
                if pattern[j + 1] == pattern[i]:
                    j += 1
                prefix[i] = j
            return prefix

        prefix = getPrefix(s)
        return prefix[-1] != -1 and \
               (prefix[-1] + 1) % (len(s) - prefix[-1] - 1) == 0
[2]:
sol = Solution1()

s = "abab"
assert sol.repeatedSubstringPattern(s) == True

s = "aba"
assert sol.repeatedSubstringPattern(s) == False

s = "abcabcabcabc"
assert sol.repeatedSubstringPattern(s) == True
[7]:
class Solution2(object):
    def repeatedSubstringPattern(self, s):
        """
        :type s: str
        :rtype: bool
        """
        if not s:
            return False

        ss = (s + s)[1:-1]
        # print(ss)
        return ss.find(s) != -1
[8]:
sol = Solution2()

s = "abab"
assert sol.repeatedSubstringPattern(s) == True

s = "aba"
assert sol.repeatedSubstringPattern(s) == False

s = "abcabcabcabc"
assert sol.repeatedSubstringPattern(s) == True